package objectmodel

import (
	"energy-amiot-platform/core"
	"energy-amiot-platform/model/dbspo"
	"energy-amiot-platform/model/request"
	"energy-amiot-platform/repository"
	"energy-amiot-platform/utils/respout"
	"errors"

	"github.com/gin-gonic/gin"
)

var (
	moduleCode = 4
)

func create(ctx *gin.Context) {
	var handleCode = 1
	var req request.ModelAddReq
	err := ctx.ShouldBindJSON(&req)
	if err != nil {
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 0, respout.StrErrParse, err, nil)
		return
	}

	value, _ := ctx.Get("product")
	var product = value.(*dbspo.Product)
	var model dbspo.Model
	model.Pid = product.ID
	model.Name = req.Name
	model.Content = dbspo.JsonField(req.Data)

	db := core.DATABASE.Cur()
	tx, b := repository.OBJECTMODEL.ExistByProductIdAndName(db, product.ID, model.Name)
	switch {
	case tx.Error != nil:
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 1, respout.StrFail, tx.Error, nil)
		return
	case b == true:
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 2, respout.StrFail, errors.New("服务标识重复"), nil)
		return
	}

	tx = repository.OBJECTMODEL.AddOne(tx, &model)
	if tx != nil {
		respout.SendError(ctx, core.APP.Code, moduleCode, handleCode, 3, respout.StrFail, tx.Error, nil)
		return
	}
	respout.Ok(ctx, nil)
}
